﻿using AvaloniaDevice.Common.Services;
using AvaloniaDevice.Common.WIFI;
using AvaloniaWindow.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks; 

//[assembly: Avalonia.Metadata.RuntimeDependency(typeof(WindowsWifiService))]
namespace AvaloniaWindow.Core
{
    public class WindowsWifiService : IWifiService
    {
        private const string WifiInterfaceName = "Wi-Fi";
        private string _interfaceGuid;

        public bool IsWifiEnabled()
        {
            try
            {
                string output = ExecuteCommand("netsh interface show interface");
                return output.Contains($"{WifiInterfaceName}\\r\\n") &&
                       output.IndexOf($"{WifiInterfaceName}\\r\\n") > -1 &&
                       output.IndexOf("已启用", output.IndexOf($"{WifiInterfaceName}\\r\\n")) > -1;
            }
            catch
            {
                return false;
            }
        }

        public async Task SetWifiEnabled(bool enabled)
        {
            string status = enabled ? "enable" : "disable";
            await ExecuteCommandAsync($"netsh interface set interface \"{WifiInterfaceName}\" {status}");
            await Task.Delay(1000);
        }

        public async Task<List<WifiInfo>> GetAvailableNetworks()
        {
            var result = new List<WifiInfo>();

            if (!IsWifiEnabled())
                return result;

            try
            {
                // 获取WiFi接口GUID
                if (string.IsNullOrEmpty(_interfaceGuid))
                {
                    string interfaceOutput = ExecuteCommand("netsh wlan show interfaces");
                    var match = Regex.Match(interfaceOutput, @"GUID\s+:\s+(\S+)");
                    if (match.Success)
                    {
                        _interfaceGuid = match.Groups[1].Value;
                    }
                }

                // 扫描网络
                await ExecuteCommandAsync("netsh wlan show networks mode=Bssid");
                await Task.Delay(2000);

                // 获取扫描结果
                string output = await ExecuteCommandAsync("netsh wlan show networks mode=Bssid");
                var networks = ParseWifiNetworks(output);

                return networks;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"扫描WiFi失败: {ex.Message}");
                return result;
            }
        }

        public async Task<bool> ConnectToWifi(string ssid, string password = null)
        {
            try
            {
                // 检查是否已存在该网络配置文件
                string profilesOutput = await ExecuteCommandAsync("netsh wlan show profiles");
                bool profileExists = profilesOutput.Contains($"\"{ssid}\"");

                if (!profileExists)
                {
                    // 创建新的网络配置文件
                    string profileXml = CreateWifiProfileXml(ssid, password);
                    string tempFile = System.IO.Path.GetTempFileName();
                    System.IO.File.WriteAllText(tempFile, profileXml);

                    await ExecuteCommandAsync($"netsh wlan add profile filename=\"{tempFile}\"");
                    System.IO.File.Delete(tempFile);
                }

                // 连接到网络
                string connectOutput = await ExecuteCommandAsync($"netsh wlan connect name=\"{ssid}\"");
                return connectOutput.Contains("已成功完成连接请求");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"连接WiFi失败: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> DisconnectFromWifi(string ssid)
        {
            try
            {
                string output = await ExecuteCommandAsync("netsh wlan disconnect");
                return output.Contains("已成功断开连接");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"断开WiFi失败: {ex.Message}");
                return false;
            }
        }

        public WifiInfo GetConnectedWifi()
        {
            try
            {
                string output = ExecuteCommand("netsh wlan show interfaces");
                var ssidMatch = Regex.Match(output, @"SSID\s+:\s+(.+)\r");
                var bssidMatch = Regex.Match(output, @"BSSID\s+:\s+(.+)\r");
                var signalMatch = Regex.Match(output, @"信号\s+:\s+(\d+)%");
                var stateMatch = Regex.Match(output, @"状态\s+:\s+(.+)\r");

                if (ssidMatch.Success && stateMatch.Success && stateMatch.Groups[1].Value == "已连接")
                {
                    return new WifiInfo
                    {
                        Ssid = ssidMatch.Groups[1].Value,
                        Bssid = bssidMatch.Success ? bssidMatch.Groups[1].Value : "",
                        SignalStrength = signalMatch.Success ? int.Parse(signalMatch.Groups[1].Value) : 0,
                        IsConnected = true
                    };
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        public bool IsSupported => true;

        public string PlatformRestrictions => "需要管理员权限才能管理WiFi连接";

        // 解析WiFi网络信息
        private List<WifiInfo> ParseWifiNetworks(string output)
        {
            var networks = new List<WifiInfo>();
            var networkSections = Regex.Split(output, @"SSID \d+ : ");

            foreach (var section in networkSections.Skip(1))
            {
                var ssidMatch = Regex.Match(section, @"(.+?)\r\n");
                if (!ssidMatch.Success)
                    continue;

                string ssid = ssidMatch.Groups[1].Value;

                // 查找所有BSSID条目
                var bssidMatches = Regex.Matches(section, @"BSSID \d+ : (.+?)\r\n.+?信号\s+:\s+(\d+)%\r\n.+?身份验证\s+:\s+(.+?)\r\n");

                foreach (Match bssidMatch in bssidMatches)
                {
                    if (bssidMatch.Groups.Count < 4)
                        continue;

                    string bssid = bssidMatch.Groups[1].Value;
                    int signalStrength = int.Parse(bssidMatch.Groups[2].Value);
                    string authentication = bssidMatch.Groups[3].Value;

                    bool isEncrypted = authentication != "开放式";

                    // 只添加一次相同SSID的网络
                    if (!networks.Any(n => n.Ssid == ssid))
                    {
                        networks.Add(new WifiInfo
                        {
                            Ssid = ssid,
                            Bssid = bssid,
                            SignalStrength = signalStrength,
                            IsEncrypted = isEncrypted,
                            EncryptionType = isEncrypted ? authentication : "开放",
                            IsConnected = section.Contains("已连接")
                        });
                    }
                }
            }

            return networks;
        }

        // 创建WiFi配置文件XML
        private string CreateWifiProfileXml(string ssid, string password)
        {
            bool isOpen = string.IsNullOrEmpty(password);

            return $@"<?xml version=""1.0""?>
<WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1"">
    <name>{ssid}</name>
    <SSIDConfig>
        <SSID>
            <name>{ssid}</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>auto</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>{(isOpen ? "open" : "WPA2PSK")}</authentication>
                <encryption>{(isOpen ? "none" : "AES")}</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            {(isOpen ? "" : $@"<sharedKey>
                <keyType>passPhrase</keyType>
                <protected>false</protected>
                <keyMaterial>{password}</keyMaterial>
            </sharedKey>")}
        </security>
    </MSM>
</WLANProfile>";
        }

        // 同步执行命令
        private string ExecuteCommand(string command)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {command}",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Verb = "runas" // 请求管理员权限
                }
            };

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (!string.IsNullOrEmpty(error))
                throw new Exception(error);

            return output;
        }

        // 异步执行命令
        private async Task<string> ExecuteCommandAsync(string command)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {command}",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Verb = "runas" // 请求管理员权限
                }
            };

            process.Start();

            // 异步读取输出
            string output = await process.StandardOutput.ReadToEndAsync();
            string error = await process.StandardError.ReadToEndAsync();

            await Task.Run(() => process.WaitForExit());

            if (!string.IsNullOrEmpty(error))
                throw new Exception(error);

            return output;
        }
    }
}
